import { API_URL, ClientAjax, MyAjax, upFileAjax, CODE } from '../config';
import { set_verify_deploy } from './deploy';

export const set_user_info = 'set_user_info';
export const set_user_avatar = 'set_user_avatar';
export const set_user_nick = 'set_user_nick';
export const set_team_name = 'set_team_name';

export function function_set_teamname (teamname, dispatch, cb) {
  MyAjax(API_URL.setTeamName, {
    teamName: teamname
  }, (result) => {
    if (result.code === CODE.SUCCESS) {
      dispatch({
        type: set_team_name,
        name: teamname
      });
      cb();
    }
  });
}

/**
 * 获取用户信息
 * @param {*} dispatch 
 */
export function function_getuserinfo (dispatch) {
  MyAjax(API_URL.getUserInfo, {}, (result) => {
    let userinfo = result.data;
    let organizeEntity = userinfo.organizeEntity;
    if (organizeEntity.deployUrl != null) {
      //验证部署地址是否可以访问
      ClientAjax(organizeEntity.deployUrl, API_URL.ckVersion, {}, function (result) {
        let newVersion = null;
        if (result.code === 1003) {
          newVersion = result.data;
        }
        dispatch({
          type: set_verify_deploy,
          result: true,
          newVersion
        });
      });
    }
    dispatch({
      type: set_user_info,
      avatar: userinfo.avatar,
      nickname: userinfo.nickname,
      email: userinfo.email,
      roleList: userinfo.roleList,
      projectList: userinfo.projectList,
      organizeEntity: organizeEntity,
    });
  });
}

export function function_set_nickname (nickname, cb, dispatch) {
  MyAjax(API_URL.setMineNick, {
    username: nickname
  }, result => {
    if (result.code === CODE.SUCCESS) {
      cb(nickname);
      dispatch({
        type: set_user_nick,
        nickname: nickname
      });
    }
  });
}

export function function_set_mine_avatar (avatar, cb, dispatch) {
  upFileAjax(API_URL.setMineAvatar, {
    avatar: avatar
  }, result => {
    if (result.code === CODE.SUCCESS) {
      cb(result.data);
      dispatch({
        type: set_user_avatar,
        avatar: result.data
      });
    } else {
      alert(result.message);
    }
  })
}

export function function_removeRoleByProject (tuid, projectId, role, cb) {
  MyAjax(API_URL.rmRole, {
    projectId,
    tuid,
    role
  }, result => {
    cb(result);
  });
}

/**
 * 项目添加用户
 * @param {int} projectId 
 * @param {string} email 
 * @param {string} nickname 
 * @param {array} roleList 
 * @param {function} cb 
 */
export function function_addMemberByProject (projectId, email, nickname, roleList, dispatch, cb) {
  MyAjax(API_URL.addMemberByProject, {
    email,
    nickname,
    roleList,
    projectId
  }, result => {
    function_getuserinfo(dispatch);
    cb(result);
  });
}